package router

import (
	"background/http/api/dto"
	"background/http/api/helper"
	"background/model/back/entity"
	"background/model/back/srv"
	"background/utilx/ginx"
	"github.com/gin-gonic/gin"
)

type CloudPlan struct {
	api srv.CloudPlan
}

func NewCloudPlan(api srv.CloudPlan) CloudPlan {
	return CloudPlan{api}
}
func (p CloudPlan) InitRouter(group *gin.RouterGroup) {
	gg := group.Group("plan")
	// 关闭验证
	gg.POST("/add", p.InsertOne())
	gg.POST("/del", p.DelById())
	gg.POST("/upd", p.UpdateById())
	gg.POST("/search", p.GetBySelf())
	gg.POST("/get", p.GetById())
}

// ======================
func (p CloudPlan) InsertOne() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		var rec entity.CloudPlan
		if ginx.BodyJsonWithErr[entity.CloudPlan](ctx, &rec) {
			return
		}
		err := p.api.InsertOne(ctx.Request.Context(), rec)

		if err != nil {
			helper.ErrorWithMsg(ctx, 400, err.Error())
			return
		}
		helper.SuccessWithMsg(ctx, "success")
	}
}
func (p CloudPlan) DelById() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		var rec entity.CloudPlan
		if ginx.BodyJsonWithErr[entity.CloudPlan](ctx, &rec) {
			return
		}
		data, err := p.api.DelById(ctx.Request.Context(), rec.ID)
		if err != nil {
			helper.ErrorWithMsg(ctx, 400, err.Error())
			return
		}

		helper.SuccessData(ctx, data)
	}
}
func (p CloudPlan) UpdateById() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		var rec entity.CloudPlan
		if ginx.BodyJsonWithErr[entity.CloudPlan](ctx, &rec) {
			return
		}
		err := p.api.UpdateById(ctx.Request.Context(), &rec)
		if err != nil {
			helper.ErrorWithMsg(ctx, 400, err.Error())
			return
		}
		helper.SuccessWithMsg(ctx, "success")
	}
}
func (p CloudPlan) GetBySelf() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		var rec dto.SearchWithPage[entity.CloudPlan]
		if ginx.BodyJsonWithErr[dto.SearchWithPage[entity.CloudPlan]](ctx, &rec) {
			return
		}

		var (
			data any
			err  error
		)
		//forceRedis := ctx.GetBool(constant.MediaRedisForce)
		//isAdmin := ctx.GetBool(constant.MediaIsAdmin)
		data, err = p.api.GetBySelf(ctx.Request.Context(), rec)
		//data, err = p.api.GetBySelfCache(forceRedis, rec)
		if err != nil {
			helper.ErrorWithMsg(ctx, 400, err.Error())
			return
		}
		helper.SuccessData(ctx, data)
		return
	}
}
func (p CloudPlan) GetById() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		var rec dto.FindByIds
		if ginx.BodyJsonWithErr[dto.FindByIds](ctx, &rec) {
			return
		}
		var (
			data any
			err  error
		)
		//forceRedis := ctx.GetBool(constant.MediaRedisForce)
		//isAdmin := ctx.GetBool(constant.MediaIsAdmin)
		data, err = p.api.GetById(ctx.Request.Context(), rec.ID)
		if err != nil {
			helper.ErrorWithMsg(ctx, 400, err.Error())
			return
		}
		helper.SuccessData(ctx, data)
	}
}
